<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px"
      @submit.native.prevent="() => handleQuery()">
      <el-form-item label="行业" prop="serviceOrderName">
        <el-input v-model="queryParams.serviceOrderName" :placeholder="$t('please_enter', { name: '行业' })
      " clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
      $t("reset")
    }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['serviceUnit:serviceUnitType:add']">{{ $t("add") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini"
          v-hasPermi="['serviceUnit:serviceUnitType:import']" @click="handleImport">{{ $t("import") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini"
          v-hasPermi="['serviceUnit:serviceUnitType:export']" @click="handleExport">{{ $t("export") }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="unitList" @selection-change="handleSelectionChange" border
      :max-height="tableHeight" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      >
      <el-table-column label="行业名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="行业数" align="center" prop="serviceOrderCode" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{(Math.random()*100).toFixed(0)}}
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="remark" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)"
            v-hasPermi="['serviceUnit:serviceUnitType:view']">上移 </el-button>
          <el-button size="mini" type="text" @click="handleView(scope.row)"
            v-hasPermi="['serviceUnit:serviceUnitType:view']">下移 </el-button>
          <el-button size="mini" type="text" @click="handleView(scope.row)"
            v-hasPermi="['serviceUnit:serviceUnitType:view']">置顶 </el-button>

        </template>
      </el-table-column>
      <el-table-column :label="$t('action')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['serviceUnit:serviceUnitType:view']">新增二级行业</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['serviceUnit:serviceUnitType:edit']">{{ $t("modify") }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['serviceUnit:serviceUnitType:delete']">{{ $t("delete") }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" :page-sizes="[10, 20, 30, 50, 100, 200]" />

    <!-- 添加或修改服务单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="lookView">
        <el-card class="box-card" style="margin-bottom: 20px">
          <div slot="header" class="clearfix">
            <span>{{ $t("basic_information") }}</span>
          </div>
          <el-form-item :label="$t('service_order_type_name')" prop="serviceOrderName">
            <el-input v-model="form.serviceOrderName" :placeholder="$t('please_enter', { name: $t('service_order_type_name') })
      " />
          </el-form-item>
          <el-form-item :label="$t('service_order_type_code')" prop="serviceOrderCode">
            <el-input v-model="form.serviceOrderCode" :placeholder="$t('please_enter', { name: $t('service_order_type_code') })
      " />
          </el-form-item>
          <el-form-item :label="$t('remarks')" prop="remark">
            <el-input v-model="form.remark" type="textarea"
              :placeholder="$t('please_enter', { name: $t('remarks') })" />
          </el-form-item>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ $t("advance_settings") }}</span>
          </div>
          <el-form-item :label="$t('delivery_method')" prop="dispatchMode">
            <el-radio-group v-model="form.dispatchMode">
              <el-radio v-for="dict in dict.type.delivery_mode" :key="dict.value" :label="dict.value">{{ dict.label
                }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('manager')" v-if="form.dispatchMode == 2">
            <el-input :placeholder="$t('please_select', { name: $t('manager') })" v-model="checkHeadString">
              <el-button slot="append" icon="el-icon-search" @click="checkHead"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('notification')" prop="inform">
            <el-checkbox-group v-model="form.inform">
              <el-checkbox v-for="dict in dict.type.service_notice_type" :key="dict.value" :label="dict.value">
                {{ dict.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item :label="$t('inactivity_notification')" prop="noDynamicNoticeInterval">
            <div class="form-line">
              <span>{{ $t("after_notification") }}</span>
              <el-input v-model="form.noDynamicNoticeInterval" maxlength="3" oninput="value=value.replace(/[^\d]/g,'')"
                style="width: 160px; margin: 0 10px">
                <el-select v-model="form.noDynamicNoticeType" slot="append"
                  :placeholder="$t('please_select', { name: '' })" style="width: 80px">
                  <el-option :label="$t('day')" value="1"></el-option>
                  <el-option :label="$t('hour')" value="0"></el-option>
                </el-select>
              </el-input>
              <span>{{ $t("send_notification") }}</span>
            </div>
          </el-form-item>
          <el-form-item :label="$t('automaticlly_marked_as_completed')" prop="automaticMarkCompletionInterval">
            <div class="form-line">
              <span>{{ $t("after_notification") }}</span>
              <el-input v-model="form.automaticMarkCompletionInterval" maxlength="3"
                oninput="value=value.replace(/[^\d]/g,'')" style="width: 160px; margin: 0 10px">
                <el-select v-model="form.automaticMarkCompletionType" slot="append"
                  :placeholder="$t('please_select', { name: '' })" style="width: 80px">
                  <el-option :label="$t('day')" value="1"></el-option>
                  <el-option :label="$t('hour')" value="0"></el-option>
                </el-select>
              </el-input>
              <span>{{ $t("inactivity_automatically_mark_completed") }}</span>
            </div>
          </el-form-item>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!lookView">
        <el-button type="primary" @click="submitForm">{{
      $t("confirm")
    }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <importModal ref="importModal" :title="$t('import')" downloadUrl="business/service/order/downloadTemplate.do"
      uploadUrl="business/service/order/importTemplate.do" :downloadName="$t('download_template')"
      @refreshList="getList">
    </importModal>

    <!-- 选择负责人弹窗 -->
    <headModal ref="headModal" :checkData="checkHeadData" :multiple="true" @setHeadData="setHeadData"
      @setAdminUserAllList="setAdminUserAllList">
    </headModal>
  </div>
</template>

<script>
import {
  listUnit,
  getUnit,
  delUnit,
  addUnit,
  updateUnit,
} from "@/api/custom/serviceUnitType";
import headModal from "@/views/components/custom/headModal.vue";
import importModal from "@/views/components/custom/importModal.vue";
export default {
  name: "Unit",
  dicts: ["delivery_mode", "service_notice_type"],
  components: {
    headModal,
    importModal,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务单表格数据
      unitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceOrderName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serviceOrderName: [
          {
            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("service_order_type_name"),
            }),
            trigger: "blur",
          },
        ],
        serviceOrderCode: [
          {
            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("service_order_type_code"),
            }),
            trigger: "blur",
          },
        ],
        dispatchMode: [
          {
            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("delivery_method"),
            }),
            trigger: "change",
          },
        ],
        inform: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("notification") }),
            trigger: "blur",
          },
        ],
      },

      checkHeadData: [],
      checkHeadString: null,
      adminUserAllList: [],
      lookView: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询服务单列表 */
    getList() {
      this.loading = true;
      listUnit(this.queryParams).then((response) => {
        // this.unitList = response.data.records;
        this.unitList = [
          {
            id: 3,
            date: '2016-05-01',
            name: '教育',
            children: [
              {
                id: 31,
                date: '2016-05-01',
                name: '培训机构',

              },
              {
                id: 31,
                date: '2016-05-01',
                name: '院校',

              },
              {
                id: 4,
                date: '2016-05-01',
                name: '互联网',
                children: [
                  {
                    id: 41,
                    date: '2016-05-01',
                    name: '电子商务'
                  },
                  {
                    id: 42,
                    date: '2016-05-01',
                    name: '运营'
                  },
                  {
                    id: 43,
                    date: '2016-05-01',
                    name: '社交网络'
                  },
                  {
                    id: 44,
                    date: '2016-05-01',
                    name: '在线教育'
                  },
                  {
                    id: 45,
                    date: '2016-05-01',
                    name: '企业服务'
                  },
                ]
              },
              {
                id: 5,
                date: '2016-05-01',
                name: '生产制造'
              }




            ]
          },],

          this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serviceOrderName: null,
        serviceOrderCode: null,
        remark: null,
        dispatchMode: null,
        inform: [],
        noDynamicNoticeInterval: null,
        automaticMarkCompletionInterval: null,
        personCharge: null,
        noDynamicNoticeType: "1",
        automaticMarkCompletionType: "1",
      };
      this.checkHeadData = [];
      this.checkHeadString = null;
      this.lookView = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t("add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUnit(id).then((response) => {
        this.form = response.data;
        this.form.inform = this.form.noticeType.split(",");
        this.open = true;
        this.title = this.$t("modify");
      });
    },
    handleView(row) {
      this.reset();
      const id = row.id;
      getUnit(id).then((response) => {
        this.form = response.data;
        this.form.inform = this.form.noticeType.split(",");
        if (this.form.personCharge) {
          const checkHeadData = this.form.personCharge
            .split(",")
            .map((item) => {
              return this.adminUserAllList.find((findItem) => {
                return findItem.userId == item;
              });
            });
          this.setHeadData(checkHeadData);
        }
        this.open = true;
        this.lookView = true;
        this.title = this.$t("view");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.dispatchMode == 2) {
            if (this.checkHeadData.length) {
              this.form.personCharge = this.checkHeadData
                .map((item) => item.userId)
                .join(",");
            }
          } else {
            this.form.personCharge = null;
          }
          this.form.noticeType = this.form.inform.join(",");
          if (this.form.id != null) {
            updateUnit(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          } else {
            addUnit(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(this.$t("delete_data"))
        .then(function () {
          return delUnit(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/service/order/export",
        {
          ...this.queryParams,
        },
        `Service Order_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$refs.importModal.showModal();
    },
    checkHead() {
      this.$refs.headModal.showModal();
    },
    setHeadData(list) {
      this.checkHeadData = list;
      this.checkHeadString = list.length
        ? list.map((item) => item.userName).join(",")
        : null;
    },
    setAdminUserAllList(list) {
      this.adminUserAllList = list;
    },
  },
};
</script>
<style lang="scss" scoped>
.form-line {
  display: flex;
  align-items: center;
}
</style>
